package com.library.ui;

import com.library.model.Book;
import com.library.model.Reader;
import com.library.service.BookService;
import com.library.service.BorrowService;
import com.library.service.ReaderService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BorrowBookPanel extends JPanel {
    private JTextField readerNumberField;
    private JTextField bookNumberField;
    private BorrowService borrowService = new BorrowService();
    private ReaderService readerService = new ReaderService();
    private BookService bookService = new BookService();

    public BorrowBookPanel() {
        setLayout(new GridLayout(3, 2));

        JLabel readerNumberLabel = new JLabel("读者编号：");
        readerNumberField = new JTextField();
        JLabel bookNumberLabel = new JLabel("书号：");
        bookNumberField = new JTextField();
        JButton borrowBtn = new JButton("借书");

        borrowBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String readerNumber = readerNumberField.getText();
                String bookNumber = bookNumberField.getText();

                Reader reader = readerService.getReaderByNumber(readerNumber);
                Book book = bookService.getBookByNumber(bookNumber);

                if (reader == null) {
                    JOptionPane.showMessageDialog(null, "读者编号不存在");
                    return;
                }
                if (book == null) {
                    JOptionPane.showMessageDialog(null, "书号不存在");
                    return;
                }

                if (borrowService.borrowBook(readerNumber, bookNumber)) {
                    JOptionPane.showMessageDialog(null, "借书成功");
                } else {
                    JOptionPane.showMessageDialog(null, "借书失败，可能是读者借书已达上限或图书库存不足");
                }
            }
        });

        add(readerNumberLabel);
        add(readerNumberField);
        add(bookNumberLabel);
        add(bookNumberField);
        add(new JLabel());
        add(borrowBtn);
    }
}